package com.server.game.logic;

import org.joda.time.DateTime;
import com.server.util.LogUtil;

/**
 * 管理全局的心跳（帧）处理
 */
public class TickManager implements Runnable {

    private static final TickManager instance = new TickManager();

    public static TickManager getInstance() {
        return instance;
    }

    private long checkTime = 0L;

    private static long TICK_PER = 1000L;

    private Thread thread = new Thread(this);

    private boolean start = false;

    private boolean interrupt = false;

    public void init() {
        if (!this.start) {
            this.start = true;
            this.thread.start();
        }
    }

    @Override
    public void run() {
        while (this.start && !this.interrupt) {
            long now = System.currentTimeMillis();
            if (now - this.checkTime < TICK_PER) {
                try {
                    Thread.sleep(TICK_PER);
                    if (this.start) {
                        this.interrupt = true;
                    }
                } catch (InterruptedException e) {
                    LogUtil.game.error("Exception", e);
                    break;
                }
            }
            this.checkTime = now;
            //tick逻辑
            DateTime dateTime = new DateTime();
            LogUtil.game.debug("全局tick【" + dateTime.toString("E MM/dd/yyyy HH:mm:ss.SSS") + "】");
        }
    }

    public void close() {
        LogUtil.game.info("TickManager close begin");
        this.start = false;
        try {
            while (true) {
                Thread.sleep(TICK_PER);
                if (this.interrupt) {
                    this.thread.interrupt();
                    break;
                }
            }
        } catch (InterruptedException e) {
            LogUtil.game.error("Exception", e);
        }
        LogUtil.game.info("TickManager close end");
    }

}
